import Cookies from 'js-cookie'
import { defineStore } from 'pinia'

import { accountErrorMap, ResultEnum } from '@/apis/http/httpEnum'
import type { CommonParams } from '@/apis/model/_utils'
import type { UserInfoModel } from '@/apis/model/auth'
import { storesKey } from '@/config'
import router from '@/router'

export const useAppStore = defineStore(
  storesKey.app,
  () => {
    const token = ref<string | undefined>()
    const userInfo = ref<Partial<UserInfoModel>>({})
    const isLogined = computed(() => !!token.value)

    const loginErrorResult = ref<{
      code: number
      message: string
      type: 'account' | 'password'
    }>()

    const websiteConfig = reactive({
      title: import.meta.env.VITE_APP_TITLE,
      logo: ''
    })

    // const avatar = ref(Avatar)

    /**
     * 获取网站标题，logo等信息
     */
    const getWebsiteConfig = () => {
      websiteConfigApi().then(res => {
        const title = res.title
        if (title) {
          document.title = title
          websiteConfig.title = title
          localStorage.setItem('__CACHE_TITLE__', title)
        }

        websiteConfig.logo = res.website_logo
          ? mergeBaseURL(res.website_logo)
          : LogoDefaultURL
      })
    }

    // 设置ico
    watch(
      () => websiteConfig.logo,
      value => {
        const ico = document.getElementById('favicon')!
        ico.setAttribute('href', value)
      }
    )

    /**
     * 登录
     */
    const login = async (
      data: Required<CommonParams<'/v1/session', 'post'>>
    ) => {
      const res = await signInApi(data)

      if (res.code === ResultEnum.SUCCESS) {
        const data = res.data
        loginErrorResult.value = undefined
        userInfo.value = data.admin
        token.value = data.token
        Cookies.set('token', token.value!, { sameSite: 'lax' })
        const redirect = router.currentRoute.value.query.redirect as string
        router.replace(redirect || '/')
      } else {
        if (
          [ResultEnum.ACCOUNT_NOT_EXIST, ResultEnum.WRONG_PASSWORD].includes(
            res.code
          )
        ) {
          loginErrorResult.value = {
            code: res.code,
            message: '账号或者密码错误，请重试',
            type: 'password'
          }
        } else {
          const type = accountErrorMap.includes(res.code)
            ? 'account'
            : 'password'

          loginErrorResult.value = {
            type,
            code: res.code,
            message: res.message
          }
        }
        throw new Error('login error')
      }
    }
    /**
     * 清楚用户信息
     */
    const clearUserInfo = () => {
      token.value = undefined
      userInfo.value = {}
    }

    /**
     * 不调用接口，仅退出
     */
    const signOut = () => {
      clearUserInfo()
      const fullPath = router.currentRoute.value.fullPath
      const redirect = router.currentRoute.value.query.redirect as string
      router.replace({
        name: 'SignIn',
        query: { redirect: redirect || fullPath }
      })
    }

    /**
     * 退出登录
     */
    const signOutAction = async () => {
      try {
        return await signOutApi()
      } finally {
        clearUserInfo()
        const fullPath = router.currentRoute.value.fullPath
        const redirect = router.currentRoute.value.query.redirect as string
        router.replace({
          name: 'SignIn',
          query: { redirect: redirect || fullPath }
        })
      }
    }

    const signOutNoJump = () => {
      signOutApi().finally(() => {
        clearUserInfo()
      })
    }

    return {
      loginErrorResult,
      isLogined,
      userInfo,
      token,
      login,
      signOut,
      clearUserInfo,
      signOutNoJump,
      signOutAction,
      websiteConfig,
      getWebsiteConfig
    }
  },
  { persist: true }
)
